/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.persistence.memory;

import apus.entity.AbstractEntity;
import apus.persistence.AbstractDAO;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * The <code>AbstractMemoryDAO</code> class represents functionality for every
 * DAO, working with memory.
 * Methods {@link #getDataSource() getDataSource} and
 * {@link #getAndIncreaseCounter()  getAndIncreaseCounter} are
 * used to work with collections of every implementation of this class.
 * @author  Maxim Vasilevsky
 * @author  Roman Dyatkovsky
 * @since APUS v0.2
 * @see AbstractDAO
 */
public abstract class AbstractMemoryDAO<EntityType extends AbstractEntity> implements AbstractDAO<EntityType> {
    
    /**
     * Receive collection from concrete implementation.
     * @return Collection of entities.
     */
    protected abstract Map <Integer,EntityType> getDataSource();
    private static Integer counter=1;
    
    /**
     * Receive counter required to work with collection.
     * @return Counter.
     */
    protected abstract Integer getAndIncreaseCounter();
    
    @Override
    public void create(EntityType entity) {
        entity.setId(counter++);
        update(entity);
    }

    @Override
    public EntityType read(int id) {
        return getDataSource().get(id);
    }

    @Override
    public void update(EntityType entity) {
        getDataSource().put(entity.getId(),entity);
    }

    @Override
    public void delete(EntityType entity) {
        getDataSource().remove(entity.getId());
    }

    @Override
    public List<EntityType> findAll() {
        return new ArrayList<>(getDataSource().values());
    }
    
}
